using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.IO;
using PocketLibrary;
using PocketLibrary.Storage;
using PocketSettings;

namespace PocketApps
{
    public partial class OpenomyMain : Form
    {

        //TBSettings.Settings Settings = TBSettings.Settings.Create();

        Openomy myOpenomy;
        bool gettingFiles = false;
        string uploadFile;
        bool uploading = false;
        Thread uploadThread;

        int smallsize = DpiHelper.Scale(16);
        int mediumsize = DpiHelper.Scale(32);

        ImageList tagSmallImageList;
        ImageList tagMediumImageList;
        PocketSettings.PocketSettings milkSettings = PocketSettings.PocketSettings.Create();

        struct OpenomyTag
        {
            public string TagName;
            public string TagId;
            public override string ToString()
            {
                return TagName;
            }
        }

        public OpenomyMain()
        {
            InitializeComponent();
        }

        private void GetTags()
        {
            Cursor.Current = Cursors.WaitCursor;
            Hashtable tags = myOpenomy.GetAllTags();
            lvTags.Invoke(new EventHandler(delegate
            {
                lvTags.Items.Clear();
            }));

            comboBox1.Invoke(new EventHandler(delegate
            {
                comboBox1.Items.Clear();
            }));
            foreach (DictionaryEntry myDE in tags)
            {
                lvTags.Invoke(new EventHandler(delegate
                {
                    lvTags.Items.Add(new ListViewItem(new string[] { myDE.Key.ToString(), myDE.Value.ToString() }));
                    lvTags.Items[lvTags.Items.Count - 1].ImageIndex = 1;

                    OpenomyTag myTag = new OpenomyTag();
                    myTag.TagName = myDE.Key.ToString();
                    myTag.TagId = myDE.Value.ToString();

                    comboBox1.Items.Add(myTag);
                    MenuItem miAddTag = new MenuItem();
                    miAddTag.Text = myTag.TagName;
                    miAddTag.Click += new EventHandler(menuItem8_Click);
                    miTags.MenuItems.Add(miAddTag);

                }));
            }
            if (comboBox1.Items.Count > 0)
            {
                comboBox1.Invoke(new EventHandler(delegate
                {
                    comboBox1.SelectedIndex = 0;
                }));
            }
            Cursor.Current = Cursors.Default;
        }

        private void Authorize()
        {
            try
            {
                if (myOpenomy.AuthorizeUser())
                {
                    Thread workerThread = new Thread(GetTags);
                    workerThread.IsBackground = true;
                    workerThread.Start();
                    //GetTags();
                }
            }
            catch (ThreadAbortException)
            { }
            finally
            {
            }
        }

        private void OpenomyMain_Load(object sender, EventArgs e)
        {
            //openomyasetukset.LueTiedostosta("\\tasku.txt");
            myOpenomy = new Openomy(
                milkSettings.SelectedUserProfile.Settings.Get("openomyUsername"),
                milkSettings.SelectedUserProfile.Settings.Get("openomyPassword"),
                "9c83b72494fd66476e9ceaf2721fd397", "10575107");

            myOpenomy.OnTransfer += new Openomy.TransferProgressHandler(myOpenomy_OnTransfer);
            myOpenomy.OnTransferComplete += new Openomy.TransferProgressHandler(myOpenomy_OnTransferComplete);
            myOpenomy.OnTransfedFailed += new EventHandler(myOpenomy_OnTransfedFailed);

            tagSmallImageList = new ImageList();
            tagMediumImageList = new ImageList();
            tagSmallImageList.ImageSize = new Size(smallsize, smallsize);
            tagMediumImageList.ImageSize = new Size(mediumsize, mediumsize);
            foreach (Image img in imageList1.Images)
            {
                tagSmallImageList.Images.Add(img);
                tagMediumImageList.Images.Add(img);
            }
            lvTags.SmallImageList = tagSmallImageList;
            lvFiles.SmallImageList = tagSmallImageList;

            Thread autThread = new Thread(Authorize);
            autThread.IsBackground = true;
            autThread.Start();
        }

        void myOpenomy_OnTransfedFailed(object sender, EventArgs e)
        {
            MessageBox.Show("File transfer failed", "Failure");
        }

        void myOpenomy_OnTransferComplete(FileTransferArgs args)
        {
            uploading = false;
            progressBar1.Invoke(new EventHandler(delegate
            {
                progressBar1.Visible = false;
            }));
            button3.Invoke(new EventHandler(delegate
            {
                button3.Enabled = false;
            }));
            //MessageBox.Show("filetransfer complete");
        }

        void myOpenomy_OnTransfer(FileTransferArgs args)
        {
            progressBar1.Invoke(new EventHandler(delegate
            {
                progressBar1.Value = (int)args.ProgressPercentage;
            }));
        }

        private void GetFiles()
        {
            if (!gettingFiles)
            {
                gettingFiles = true;
                Cursor.Current = Cursors.WaitCursor;
                Hashtable files = myOpenomy.GetTag(long.Parse(lvTags.Items[lvTags.SelectedIndices[0]].SubItems[1].Text));
                lvFiles.Invoke(new EventHandler(delegate
                {
                    lvFiles.Items.Clear();
                }));
                foreach (DictionaryEntry myDE in files)
                {
                    lvFiles.Invoke(new EventHandler(delegate
                    {
                        lvFiles.Items.Add(new ListViewItem(new string[] { myDE.Key.ToString(), myDE.Value.ToString() }));
                        string extension = myDE.Key.ToString();
                        extension = extension.Substring(extension.LastIndexOf(".") + 1).ToLower();
                        if (extension == "zip" || extension == "rar" || extension == "cab")
                            lvFiles.Items[lvFiles.Items.Count - 1].ImageIndex = 3;
                        else if (extension == "jpg" || extension == "png" || extension == "gif" || extension == "bmp")
                            lvFiles.Items[lvFiles.Items.Count - 1].ImageIndex = 4;
                        else if (extension == "mp3" || extension == "ogg" || extension == "wav" || extension == "aac")
                            lvFiles.Items[lvFiles.Items.Count - 1].ImageIndex = 5;
                        else if (extension == "exe" || extension == "msi")
                            lvFiles.Items[lvFiles.Items.Count - 1].ImageIndex = 2;
                        else
                            lvFiles.Items[lvFiles.Items.Count - 1].ImageIndex = 6;
                    }));
                }
                gettingFiles = false;
                Cursor.Current = Cursors.Default;
            }
        }

        private void lvTags_ItemActivate(object sender, EventArgs e)
        {
            if (lvTags.SelectedIndices.Count > 0)
            {
                tabControl1.TabIndex = 1;
                Thread workerThread = new Thread(GetFiles);
                workerThread.IsBackground = true;
                workerThread.Start();
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // TODO: change available toolbar buttons

        }

        private void DownloadFile()
        {
            Cursor.Current = Cursors.WaitCursor;
            this.Invoke(new EventHandler(delegate
            {
                menuItem10.Enabled = false;
                menuItem9.Enabled = false;

            }));
            long fileId = long.Parse(lvFiles.Items[lvFiles.SelectedIndices[0]].SubItems[1].Text);
            OpenomyFile of = myOpenomy.GetFile(fileId, 5, true);
            string path = milkSettings.SelectedUserProfile.Settings.Get("dataFolder") + "\\";

            using (FileStream fs = new FileStream(
                path + of.fileName,
                FileMode.Create, FileAccess.Write, FileShare.Write))
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(of.fileData, 0, of.fileData.Length);
            }
            //MessageBox.Show("Download complete.", "Download");
            this.Invoke(new EventHandler(delegate
            {
                menuItem9.Enabled = true;
                menuItem10.Enabled = true;
            }));
            Cursor.Current = Cursors.Default;
        }

        private void lvFiles_ItemActivate(object sender, EventArgs e)
        {
            /*
            if (lvFiles.SelectedIndices.Count > 0)
            {
                progressBar1.Value = 0;
                progressBar1.Visible = true;

                Thread downloadThread = new Thread(DownloadFile);
                downloadThread.IsBackground = true;
                downloadThread.Start();
            }
            /**/
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (ofdOpenomy.ShowDialog() == DialogResult.OK)
            {
                uploadFile = ofdOpenomy.FileName;
                textBox1.Text = uploadFile.Substring(uploadFile.LastIndexOf("\\") + 1);
                button2.Enabled = true;
            }
        }

        void TUploadFile()
        {
            if (!uploading)
            {
                uploading = true;
                Cursor.Current = Cursors.WaitCursor;
                FileInfo myUpload = new FileInfo(uploadFile);

                #region read filecontents
                /**/
                byte[] filedata = new byte[myUpload.Length];

                using (FileStream fs = new FileStream(uploadFile, FileMode.Open, FileAccess.Read))
                using (BinaryReader br = new BinaryReader(fs))
                {
                    br.Read(filedata, 0, filedata.Length);
                }
                /**/
                #endregion

                #region selec tagID
                OpenomyTag myTag = new OpenomyTag();
                comboBox1.Invoke(new EventHandler(delegate
                {
                    myTag = (OpenomyTag)comboBox1.SelectedItem;
                }));
                #endregion

                #region select filename
                string filename = myUpload.Name;
                textBox1.Invoke(new EventHandler(delegate
                {
                    filename = textBox1.Text;
                    textBox1.Text = "";
                }));
                #endregion

                uploading = false;
                myOpenomy.AddFile(filename, filedata, long.Parse(myTag.TagId));
                Cursor.Current = Cursors.Default;
                //myOpenomy.AddFileAlternative(myUpload, long.Parse(myTag.TagId));
                //MessageBox.Show("Upload finished.", "Upload");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            button3.Enabled = true;
            progressBar1.Value = 0;
            progressBar1.Visible = true;

            uploadThread = new Thread(TUploadFile);
            uploadThread.IsBackground = true;
            uploadThread.Start();
            //TUploadFile();
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            using (OpenomyNewTag opTag = new OpenomyNewTag())
            {
                if (opTag.ShowDialog() == DialogResult.OK)
                {
                    myOpenomy.CreateTag(opTag.tbTag.Text);
                    Thread workerThread = new Thread(GetTags);
                    workerThread.IsBackground = true;
                    workerThread.Start();
                }
            }
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            if (myOpenomy.DeleteFile(long.Parse(lvFiles.Items[lvFiles.SelectedIndices[0]].SubItems[1].Text)))
                lvFiles.Items.Remove(lvFiles.Items[lvFiles.SelectedIndices[0]]);
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            if (myOpenomy.DeleteTag(long.Parse(lvTags.Items[lvTags.SelectedIndices[0]].SubItems[1].Text)))
            {
                int ret = -1;
                for (int i = 0; i < comboBox1.Items.Count; i++)
                {
                    if (comboBox1.Items[i].ToString() == lvTags.Items[lvTags.SelectedIndices[0]].Text)
                        ret = i;
                }
                comboBox1.Items.RemoveAt(ret);

                lvTags.Items.Remove(lvTags.Items[lvTags.SelectedIndices[0]]);
            }

        }

        private void menuItem8_Click(object sender, EventArgs e)
        {
            long fileId = long.Parse(lvFiles.Items[lvFiles.SelectedIndices[0]].SubItems[1].Text);

            long tagId = -1;
            for (int i = 0; i < lvTags.Items.Count; i++)
            {
                ListViewItem li = lvTags.Items[i];
                if (li.Text == ((MenuItem)sender).Text)
                {
                    tagId = long.Parse(li.SubItems[1].Text);
                    break;
                }
            }
            myOpenomy.AddFileToTag(fileId, tagId);
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            long fileId = long.Parse(lvFiles.Items[lvFiles.SelectedIndices[0]].SubItems[1].Text);
            long tagId = long.Parse(lvTags.Items[lvTags.SelectedIndices[0]].SubItems[1].Text);

            if (myOpenomy.DeleteFileFromTag(fileId, tagId))
                lvFiles.Items.Remove(lvFiles.Items[lvFiles.SelectedIndices[0]]);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (uploadThread != null)
                uploadThread.Abort();
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            if (lvFiles.SelectedIndices.Count > 0)
            {
                progressBar1.Value = 0;
                progressBar1.Visible = true;

                Thread downloadThread = new Thread(DownloadFile);
                downloadThread.IsBackground = true;
                downloadThread.Start();
            }
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            if (lvFiles.SelectedIndices.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                long fileId = long.Parse(lvFiles.Items[lvFiles.SelectedIndices[0]].SubItems[1].Text);
                OpenomyFile of = myOpenomy.GetFile(fileId, 1, false);
                string shortfilename = of.fileName;
                if (shortfilename.Length > 20)
                    shortfilename = shortfilename.Remove(20, shortfilename.Length - 20);

                sb.Append("Filename " + shortfilename + "\r\n");
                sb.Append("Size\r\n" + of.size + " bytes \r\n");

                MessageBox.Show(sb.ToString(), "File details", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            }


        }

        private void menuItem10_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        private void OpenomyMain_Resize(object sender, EventArgs e)
        {
            tabControl1.Height = this.Height - tabControl1.Top;

        }
    }
}